package com.peng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peng.common.R;
import com.peng.entity.Category;
import com.peng.entity.Dish;
import com.peng.entity.Employee;
import com.peng.entity.Setmeal;
import com.peng.handler.CustomException;
import com.peng.service.CategoryService;
import com.peng.mapper.CategoryMapper;
import com.peng.service.DishService;
import com.peng.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
* @author dell
* @description 针对表【category(菜品及套餐分类)】的数据库操作Service实现
* @createDate 2022-05-21 19:56:09
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;


    @Override
    public Page pageR(Integer page, Integer pageSize, String name) {
        Page<Category> objectPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        Page<Category> employeePage = baseMapper.selectPage(objectPage, queryWrapper);
        return employeePage;
    }

    @Override
    public void remove(Long ids) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,ids);
        int count = dishService.count(dishLambdaQueryWrapper);
        if (count>0){
            throw new CustomException("当前菜品分类被关联，无法删除");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,ids);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2>0){
            throw new CustomException("当前套餐分类被关联，无法删除");
        }
        baseMapper.deleteById(ids);
    }

    @Override
    public List<Category> listR(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null,Category::getType,category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = baseMapper.selectList(queryWrapper);
        return list;

    }
}




